package com.frame.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.frame.config.Result;
import com.frame.config.UploadMinioUtils;
import com.frame.domain.AgrGrowRecords;
import com.frame.domain.City;
import com.frame.domain.Crop;
import com.frame.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CropController {
    @Autowired
    CropService cropService;
    @Autowired
    PlantationIdService plantationIdService;
    @Autowired
    UserService userService;
    @Autowired
    CityService cityService;
    @Autowired
    plantingMethodService plantingMethodService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;


    private static String accessKey="3BYoenoEcIw0Rq6K";

    private static String secretKey="wBmgIWZ1eMafk22UmsV98TEQUsdAQAG0";


    private static String bucketName="2112a";


    //农作物表查询
    @RequestMapping("list")
    public Result list(@RequestBody Crop crop,Integer current,Integer size){
        if (crop.getName()==null){
            Object list = redisTemplate.opsForValue().get("list");
            System.out.println(list);
            if (list!=null){
                return Result.success(list);
            }
        }
        String lockKey="cropListLook";
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean b = lock.tryLock(10, 30, TimeUnit.MINUTES);
            if (b){
                PageHelper.startPage(current, size);
                List<Crop> list = cropService.list(crop);
                return Result.success(new PageInfo<>(list));
            }else{
                return Result.fail("当前繁忙");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }
    @RequestMapping("add")
    public Result add(@RequestBody Crop crop){
        crop.setCreateTime(new Date());
        String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
        crop.setCropEncoding(snowflakeNextIdStr);
        boolean add = cropService.add(crop);
        return  add?Result.success():Result.fail();
    }
    @RequestMapping("plist")
    public Result plist(){
        List<Crop> list = plantationIdService.plist();
        return Result.success(list);
    }
    @RequestMapping("ulist")
    public Result ulist(){
        List<Crop> list = userService.ulist();
        return Result.success(list);
    }
    @RequestMapping("pmlist")
    public Result pmlist(){
        List<Crop> list = plantingMethodService.pmlist();
        return Result.success(list);
    }



    @RequestMapping("/getCargo")
    public Result getCargo()
    {
        List<Crop> list=cropService.getProcessList();
        return Result.success(list);
    }


    @RequestMapping("gettype1")
    public Result gettype(){
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

        List<City> list = cityService.getlist();
        List<Tree<Object>> treeNodes = TreeUtil.<City, Object>build(list, 1, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCityId());
                    tree.setParentId(treeNode.getPid());
                    tree.setName(treeNode.getCityname());
                });
        return Result.success(treeNodes);
    }
    @RequestMapping("hx")
    public Result hx(Integer cropId){
        Crop list = cropService.hx(cropId);
        return Result.success(list);
    }
    @RequestMapping("img")
    public String uploadFile(MultipartFile file) throws Exception {
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint("http://127.0.0.1:9000")
                .credentials(accessKey, secretKey)
                .build();
        String filename = UUID.randomUUID() + file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs.builder().object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).bucket(bucketName)
                    .build());
        } catch (Exception e) {
            throw new Exception(e);
        }
        return "http://127.0.0.1:9000/" + bucketName + "/" + filename;
    }

    @RequestMapping("updata")
    public Result updata(@RequestBody Crop crop){
        boolean s= cropService.updata(crop);
        return s?Result.success():Result.fail();
    }
    @RequestMapping("excels")
    public  void excel(HttpServletResponse response) throws IOException {
        String fileName = URLEncoder.encode("农产品信息", "UTF-8").replaceAll("\\+", "%20");
        //设置响应的编码
        response.setCharacterEncoding("UTF-8");
        //设置响应的类型:xlsx 后缀的文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //设置响应头，告诉浏览器以下载的为一个excel表格
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Crop> data = cropService.list1();
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        EasyExcel.write(response.getOutputStream(), Crop.class).sheet("农产品信息").doWrite(data);
    }
   @RequestMapping("dr")
    public String dr(MultipartFile file) throws IOException {
       EasyExcel.read(file.getInputStream(),Crop.class,new UploadDataListener(cropService)).sheet().doRead();
       return "success";
   }
   @RequestMapping("szjl")
   public Result szjl(@RequestBody AgrGrowRecords agrGrowRecords){
        agrGrowRecords.setRecordsTime(new Date());
        if (agrGrowRecords.getIsmature() == 1){
            cropService.updatastatu(agrGrowRecords.getCropId());
        }
        boolean s= cropService.add2(agrGrowRecords);
        return  s?Result.success():Result.fail();
   }
}


